package pony.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import pony.model.CheckMemberId;

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    private List<String>members = new ArrayList<String>();
	
    public LoginServlet() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doService(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doService(request, response);
	}
	
	private void doService(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");  // 先設定以UTF-8編碼來取得Client端的請求參數
		String userId = request.getParameter("userAccount");
		String userPw = request.getParameter("userPassword");
		
//		if(userId.equals("Mia") && userPw.equals("bitch")) {
//			members.add("Mia");
//			HttpSession member = request.getSession();  // 取得HttpSession物件
//			member.setAttribute("memberList", members); // 設定Session作用域的屬性
//			
//			RequestDispatcher dispatcher = request.getRequestDispatcher("./JSPs/member.jsp");
//			// 利用請求物件取得分派器物件，引數為相對於原始請求URL的相對路徑
//			dispatcher.forward(request, response);
//		} else {
//			RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/JSPs/wrongId.jsp");
//			// 先取得ServletContext物件，把請求轉向(分派)給靜態的html頁面也可以! 
//			// 此引數必須為以Web App的環境跟目錄絕對路徑字串
//			dispatcher.forward(request, response);
//		}
		
		// 以下士利用Model來做身分驗證功能
		CheckMemberId cm = new CheckMemberId();
		if(cm.checkPw(userId, userPw)) {
			members.add(0, userId);
			HttpSession member = request.getSession();   // 取得HttpSession物件
			member.setAttribute("memberList", members);  // 設定Session作用域的屬性
			
			RequestDispatcher dispatcher = request.getRequestDispatcher("./JSPs/member.jsp");
			dispatcher.forward(request, response);
		} else {
			RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/JSPs/wrongId.jsp");
			dispatcher.forward(request, response);
		}
			
		
		
	}
}
